package com.breakfast.fun.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;

import com.breakfast.fun.BuildConfig;
import com.breakfast.fun.R;
import com.breakfast.fun.view.widget.CustomDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 版本管理
 *
 * @author dxt
 */
public class VersionUtil {

    public final static int VERSION_RESULT = 1;

    public final static int VERSION_DOWN = 2;
    public final static int VERSION_DOWNED = 3;
    public final static int VERSION_DOWN_FAIL = 4;
    private static CustomDialog dialog;


    public static String getCurrentVersion(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String versionName = info.versionName; // 版本号
            return versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 判断版本号 是否要更新
     *
     * @param netVersion   网络版本
     * @param localVersion 本地版本
     * @return
     */
    public static boolean isNeedUpdate(String netVersion, String localVersion) {
        if (!TextUtils.isEmpty(netVersion) && !TextUtils.isEmpty(localVersion)) {
            String[] netStr = netVersion.split("\\.");
            String[] localStr = localVersion.split("\\.");
            for (int i = 0; i < netStr.length; i++) {
                if (Integer.parseInt(netStr[i]) > Integer.parseInt(localStr[i])) {
                    return true;
                } else if (Integer.parseInt(netStr[i]) < Integer
                        .parseInt(localStr[i])) {
                    return false;
                }
            }
        } else {
            return false;
        }
        return false;
    }


    public static void updateVersion(Context context, final File savePath, final File ApkFile,
                                     final String address, final Handler handler, final String version) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(address);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                    int count = 0;
                    byte buf[] = new byte[1024];
                    int progress;
                    int lastRate = 0;
                    boolean canceled = false;
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        Message msg = handler.obtainMessage();

                        if (progress >= lastRate + 1) {
                            msg.what = VERSION_DOWN;
                            msg.arg1 = progress;
                            handler.sendMessage(msg);
                            lastRate = progress;
                        }
                        if (numread <= 0) {
                            // 下载完成通知安装
                            msg.what = VERSION_DOWNED;
                            handler.sendMessage(msg);
                            canceled = true;
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!canceled);

                    fos.close();
                    is.close();
                } catch (Exception e) {
                    Message msg = handler.obtainMessage();
                    msg.what = VERSION_DOWN_FAIL;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void installApk(File file, Context context) {
        if (!file.exists()) {
            return;
        }
//        Intent i = new Intent(Intent.ACTION_VIEW);
//        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//
//        if(Build.VERSION.SDK_INT == 25){
//            i.setDataAndType(Uri.parse("content://" + file.toString()),
//                    "application/vnd.android.package-archive");
//        }else {
//            i.setDataAndType(Uri.parse("file://" + file.toString()),
//                    "application/vnd.android.package-archive");
//        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {        //7.0以下的版本
            intent.setDataAndType(Uri.parse("file://" + file.toString()),
                    "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

}
